<template>
<div class="proContent">
  <div class="topThree">
    <span>
          <img src="../../../assets/images/profit2x.png" v-if="type==0" alt="" />
          <img src="../../../assets/images/loss2x.png" v-else alt="" />
        </span>
    <span class="text">{{type==0?'盈利Top 3':'亏损Top 3'}}</span>
  </div>
  <div v-show='status==0'>
    <div class="profit" v-if='haveData'>
      <ul>
        <li v-for='(item,index) in topThree ' @click='changeLabelPro(index)' :class="{'active': selectedIndex == index}">
          <p v-text='item.stockName'></p>
          <p v-text='item.totalProfit'></p>
        </li>
      </ul>
      <p class="title">
        <i>{{topThree[selectedIndex].stockName}}</i>&nbsp;:&nbsp;&nbsp;持有天数<b>{{topThree[selectedIndex].holdDay}}</b>天，每日收益额走势图
      </p>
      <div class="proAnalysisChart">
        <div ref="proTopThree" style="width:100%;height:220px"></div>
      </div>
    </div>
  </div>
  <span class="no" v-if='status==1'>
    <img src="../../../assets/images/profitNone.png" alt="">
    <div>{{type==0?proDetail:lossDetail}}</div>
  </span>
  <return-error v-if='status==2'></return-error>
</div>
</template>

<script>
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/grid'

import constant from '@/common/constant'
import RemoteDAO from '@/common/remoteDAO'
import tools from '@/common/tools'
import shPoint from '@/assets/images/shPoint.png'

let arrLength = 0;
const proOption = {
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(0,0,0,.4)',
    axisPointer: {
      type: 'line',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  color: ['#2EAAFF'],
  grid: {
    show: false,
    left: '0',
    right: '0',
    bottom: '5%',
    top: '5%',
    containLabel: true
  },
  xAxis: [{
    show: true,
    axisLine: {
      show: true,
      onZero: false,
      lineStyle: {
        color: '#c9daeb'
      }
    },
    axisLineTick: {
      show: false
    },
    axisLabel: {
      show: false
    },
    splitLine: {
      show: false
    },
    type: 'category',
    boundaryGap: false,
    axisLabel: {
      textStyle: {
        color: '#999'
      }
    },
    axisTick: {
      show: false
    }
  }],
  yAxis: [{
    show: true,
    splitNumber: 2,
    axisLine: {
      show: false
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: ['#bac9d8'],
        type: 'dotted'
      }
    },
    axisLineTick: {
      show: false
    },
    type: 'value',
    axisLabel: {
      textStyle: {
        color: '#999'
      },
      inside: true
    },
    axisTick: {
      show: false
    }
  }],
  series: [{
    name: '每日收益',
    type: 'line',
    symbol: 'image://' + shPoint,
    symbolSize: 10,
    showSymbol: false,
    areaStyle: {
      normal: {
        color: 'rgba(48,159,234,0.1)'
      }
    }
  }]
}

let addPro = []
let addLoss = []
const InterfaceArr = [
  [RemoteDAO.callZL13100048, RemoteDAO.callZL13100049],
  [RemoteDAO.callZL13100038, RemoteDAO.callZL13100039]
]

export default {
  data() {
    return {
      status: 0, // 页面状态 0--正常图表 1--empty 2--error
      haveData: false,
      selectedIndex: 0,
      topThree: [],
      proDetail: '',
      lossDetail: ''
    }
  },
  props: {
    timeIndex: {
      type: Number,
      default: 0
    },
    category: { // 盈利类型 0--股票盈亏，1--理财盈亏
      type: Number,
      default: 0
    },
    type: { // 类别，0--盈利，1--亏损
      type: Number,
      default: 0
    }
  },
  watch: {
    category: function(val, oldVal) {
      this.selectedIndex = 0;
      this.fetchData();
    },
    timeIndex: function(val, oldVal) {
      this.selectedIndex = 0;
      this.fetchData();
    }
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    proAdd(i, item) {
      if (i == 0) {
        let day_profit = item._source.day_profit.toFixed(2)
        addPro.push(day_profit)
      } else {
        let sum = parseFloat(addPro[i]) * 10000 + item._source.day_profit * 10000
        let addOption = parseFloat(sum / 10000).toFixed(2);
        addPro.push(addOption)
      }
    },

    lossAdd(i, item) {
      if (i == 0) {
        let day_profit = item._source.day_profit.toFixed(2)
        addLoss.push(day_profit)
      } else {
        let sum = parseFloat(addLoss[i]) * 10000 + item._source.day_profit * 10000
        let addOption = parseFloat(sum / 10000).toFixed(2);
        addLoss.push(addOption)
      }
    },

    changeLabelPro(index) {
      this.selectedIndex = index;
      this.fetchChartData();
    },

    fetchData() {
      this.category == 0 ? this.proDetail = constant.TimeTabData[this.timeIndex].text + '暂无盈利股票' :
        this.proDetail = constant.TimeTabData[this.timeIndex].text + '暂无盈利理财';
      this.category == 0 ? this.lossDetail = constant.TimeTabData[this.timeIndex].text + '暂无亏损股票' :
        this.lossDetail = constant.TimeTabData[this.timeIndex].text + '暂无亏损理财';
      InterfaceArr[this.type][this.category]({
        "pagenum": constant.TimeTabData[this.timeIndex].num,
        "recent": constant.TimeTabData[this.timeIndex].name
      }, this.afterFetchThreeData);
    },

    fetchChartData() {
      RemoteDAO.callZL13100030({
        "pagenum": constant.TimeTabData[this.timeIndex].num,
        'tradedate': this.$store.state.dateOptions,
        'stock_code': this.topThree[this.selectedIndex].stockCode,
        'market_code': this.topThree[this.selectedIndex].marketCode,
      }, this.ZL13100030);
    },

    afterFetchThreeData(result) {
      let vm = this;
      if (result.error == '1') {
        vm.status = 2;
        return;
      }

      let bigdata = JSON.parse(result.data).body[0].bigdata;
      let totaldata = JSON.parse(bigdata).hits.hits;

      if (totaldata.length == 0) {
        vm.status = 1;
        return;
      }
      vm.status = 0;
      vm.haveData = true;

      vm.topThree = totaldata.slice(0, 3).map((item) => {
        return {
          stockName: item._source.stock_name,
          totalProfit: item._source.total_profit.toFixed(2),
          holdDay: item._source.total_hold_days,
          stockCode: item._source.stock_code,
          marketCode: item._source.market_code
        }
      });

      this.fetchChartData();
    },
    xDataExpand(dateArr) {
      const threshHold = 15
      if (dateArr.length > threshHold) {
        return dateArr
      }

      let count = dateArr.length;
      let year = Number(dateArr[dateArr.length - 1].slice(0, 4))
      let month = Number(dateArr[dateArr.length - 1].slice(5, 7))
      let date = Number(dateArr[dateArr.length - 1].slice(8, 12))
      let now = new Date(year, month - 1, date);

      now.setDate(now.getDate() + 1);
      while (count < threshHold) {
        dateArr.push(tools.DateFormat(now, year + '/MM/dd'))
        now.setDate(now.getDate() + 1);
        count++;
      }
      return dateArr
    },
    ZL13100030(result) {
      let vm = this;

      if (result.error == '1') {
        vm.status = 2;
        return;
      }

      let bigdata = JSON.parse(result.data).body[0].bigdata;
      let specData = JSON.parse(bigdata).hits.hits;

      if (specData.length == 0) {
        vm.status = 1;
        return;
      }

      let topThreeXData = [''],
        topThreeYData = [0],
        proThreeDate = [''],
        lossThreeDate = [''];


      if (vm.type == 0) {
        addPro = [0];
      } else {
        addLoss = [0];
      }
      specData.forEach(function(item, i) {
        let tDate = item._source.tradedate + ''
        let tYear = tDate.slice(0, 4)
        let tMonth = tDate.slice(4, 6)
        let today = tDate.slice(6, 8),
          echartDate;

        tDate = tYear + '/' + tMonth + '/' + today
        echartDate = tYear + '/' + tMonth + '/' + today
        vm.type == 0 ? proThreeDate.push(echartDate) : lossThreeDate.push(echartDate)
        topThreeXData.push(tDate)

        let dayProfit = item._source.day_profit.toFixed(2)
        topThreeYData.push(dayProfit)
        vm.type == 0 ? vm.proAdd(i, item) : vm.lossAdd(i, item)
      })
      if (vm.timeIndex == 0 || vm.timeIndex == 1) {
        topThreeXData = this.xDataExpand(topThreeXData)
      }
      arrLength = topThreeXData.length

      this.$nextTick(() => {
        if (!vm.proChart) {
          vm.proChart = echarts.init(vm.$refs.proTopThree);
          vm.proChart.setOption(proOption);
        }
        vm.proChart.setOption({
          xAxis: [{
            data: topThreeXData,
            axisLabel: {
              interval: Math.ceil(arrLength / 5) - 1,
              textStyle: {
                algin: 'center',
                color: '#999'
              },
              formatter: (val, index) => {
                if (index > arrLength - 10 && index < arrLength - 2) {
                  return val
                } else if (index >= arrLength - 2) {
                  return ''
                } else {
                  return val
                }
              }
            }
          }],
          series: [{
            data: topThreeYData,
            axisLabel: {
              interval: Math.ceil(arrLength / 5) - 1,
              textStyle: {
                algin: 'center',
                color: '#999'
              },
              formatter: (val, index) => {
                if (index > arrLength - 10 && index < arrLength - 2) {
                  return val + ''
                } else if (index >= arrLength - 2) {
                  return ''
                } else {
                  return val
                }
              }
            }
          }]
        });

        vm.type == 0 ? vm.proChart.setOption({
          tooltip: {
            formatter: (params) => {
              return `${proThreeDate[params[0].dataIndex]}<br/>
              <div style="display:inline-block; width:10px; height:10px; border-radius:50%; background:${params[0].color}"></div>&nbsp;
              当日收益：${params[0].data}元<br/>
              <div style="display:inline-block; width:10px; height:10px; border-radius:50%; background:rgba(0,0,0,0)"></div>&nbsp;
              累计收益：${addPro[params[0].dataIndex]}元`
            }
          },
        }) : vm.proChart.setOption({
          tooltip: {
            formatter: (params) => {
              return `${lossThreeDate[params[0].dataIndex]}<br/>
              <div style="display:inline-block; width:10px; height:10px; border-radius:50%; background:${params[0].color}"></div>&nbsp;
              当日收益：${params[0].data}元<br/>
              <div style="display:inline-block; width:10px; height:10px; border-radius:50%; background:rgba(0,0,0,0)"></div>&nbsp;
              累计收益：${addLoss[params[0].dataIndex]}元`
            }
          },
        })
      })
    }
  }
}
</script>

<style scoped>
.proContent{
  height: 320px;
}
.active {
  color: #2eabff;
}

.lossThree,
.topThree {
  font-size: 0.12rem;
  text-align: center;
  margin-top: 0.2rem;
}

.lossThree {
  margin: 0;
}

.lossThree span img,
.topThree span img {
  display: inline-block;
  width: 0.13rem;
  height: 0.1rem;
  vertical-align: middle;
  margin-right: 0.05rem;
}

.lossThree .text,
.topThree .text {
  padding-top: 0.025rem;
  padding-bottom: 0.001rem;
  color: #555;
}

.proContent ul {
  margin-top: 0.17rem;
  font-size: 0.12rem;
  text-align: center;
  padding: 0 0.15rem 0 0.15rem;
  color: #999;
}

.proContent ul li {
  display: inline-block;
  width: 33%;
}

.active {
  color: #2eabff;
}

.title {
  font-size: 0.1rem;
  text-align: center;
  margin-top: 0.18rem;
  color: #999;
}

.title b {
  color: #E31A2E;
}

.no {
  display: block;
  color: #999;
  margin-top: 0.05rem;
  text-align: center;
}
.no img{
  display: inline-block;
  width: 170px;
  margin-top: 0.24rem;
}
.no div{
  font-size: 0.13rem;
}
</style>
